package cn.scy.interceptor;

import cn.hutool.json.JSONUtil;
import cn.scy.annotation.PassToken;
import cn.scy.business.service.UserLoginService;
import cn.scy.constant.ErrorCode;
import cn.scy.base.ResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 拦截器实现类
 *
 * @author scy
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private UserLoginService userLoginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Headers,Authorization,X-Custom-Header,X-Requested-With,uuToken");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String uri = request.getRequestURI();
        log.info("拦截器拦截的路径为：{}", uri);
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查是否有 @PassToken 注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        } else {
            response.setCharacterEncoding("UTF-8");
            final String headerToken = request.getHeader("uuToken");
            if (headerToken == null) {
                back(response);
                return false;
            }
            // 解析token信息
            try {
                if (!userLoginService.checkToken(headerToken)) {
                    back(response);
                    return false;
                }
            } catch (Exception e) {
                log.error(e.toString());
                back(response);
                return false;
            }
        }

        return true;
    }

    public void back(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.append(JSONUtil.toJsonStr(ResponseDTO.error(ErrorCode.NOT_LOGIN)));
        out.close();
        response.flushBuffer();
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
